/**
 * 角色管理JS类
 * @from role.js
 */
var PATH_PREFIX ="";

function setPathPrefix(path){
	PATH_PREFIX = path;
}

/**
 * 角色管理操作JS类
 * 
 */
var WASP_ROLE ={
		/*列表打开文件*/
		getViewHtml : function(text, options, rData){
	 		var roleId = rData["roleId"];
	 		return getHref(text, "WASP_ROLE.view('" + roleId+"')");
		},
		openEmp: function(){//打开选择员工的界面并设置层
			 OpenOrgSelect('EMPIDS','emp_nm','EMP','YES','NO','ORGorgid','NAMEX','loadlist()');
		},
		//详细界面
		view : function(roleId){ 
			var actionUrl = PATH_PREFIX+"roleDetailView.do?roleId=" + roleId;
			openDialog(actionUrl);
		},
		//新增界面
		add : function(){
			var actionUrl = PATH_PREFIX+"roleAddView.do";
			openDialog(actionUrl);
		},
		//更新
	   updateRole : function(roleId){
			var actionUrl = PATH_PREFIX+"roleUpdateView.do?roleId=" + roleId;
			openDialog(actionUrl);
	   },
	   //刷新缓存
	   refreshCached : function(){
			var actionUrl = ctx + "utils/cached/shareCached/refreshShareCached.do";
			openDialog(actionUrl);
	   },
		showShareInfo: function(){
			var roleID = $("#roleId").val()||"";//当前记录ID，需要排除
			var authType = $("input[type='radio'][name='authorityType']:checked").val();//1:普通，2:特殊
			var roleType = $("#roleType").val();//角色类型，查询参数
			var actionUrl = PATH_PREFIX+"queryRole.do?roleType="+roleType;
			var container = $("#shareInfoContainer");//页面容器
			
			if (roleType == '2') {
				$("#isDempt").val("").trigger("change");
				$("#isDempt").rules("remove","required");
				$("#isDemptDiv").hide();
				
				$("#authorityTypeDiv").hide();
				$("#shareInfoContainerDiv").hide();
				
				$("#postDiv").show();
				$('#operRoleId').rules("add", {
					required : true, messages:{required:"请选择操作角色"}
				});
				$("#operRoleDiv").show();
				$('#isDemptPer').rules("add", {
					required : true, messages:{required:"请选择是否为部门人员默认角色"}
				});
				$("#isDemptPerDiv").show();
				$("#deptDiv").show();
			} /*else if (roleType == '1') {
				$("#postId").val("").trigger("change");
				
				$("#isDempt").val("").trigger("change");
				$("#isDempt").rules("remove","required");
				$("#isDemptDiv").hide();
				
				$("#post").val("");
				$("#postDiv").hide();
				
				$("#operRoleId").val("");
				$("#operRoleId").rules("remove","required");
				$("#operRoleDiv").hide();
				
				$("#isDemptPer").val("").trigger("change");
				$("#isDemptPer").rules("remove","required");
				$("#isDemptPerDiv").hide();
				
				$("#deptId").val("").trigger("change");
				$("#deptDiv").hide();
				
				$("#authorityTypeDiv").show();
				$("#shareInfoContainerDiv").show();
			}*/ else {
				$("#isDemptDiv").show();
				$('#isDempt').rules("add", {
					required : true, messages:{required:"请选择是否为部门资源默认角色"}
				});
				$("#authorityTypeDiv").show();
				$("#shareInfoContainerDiv").show();
				
				$("#postDiv").show();
				$('#operRoleId').rules("add", {
					required : true, messages:{required:"请选择操作角色"}
				});
				$("#operRoleDiv").show();
				
				$('#isDemptPer').rules("add", {
					required : true, messages:{required:"请选择是否为部门人员默认角色"}
				});
				$("#isDemptPerDiv").show();
				
				$("#deptDiv").show();
			}
			
			if('2' == authType){
				container.html('特殊权限不能分享！');//特殊权限不可分享给别人
				return;
			}
			// 时间
			container.html('');
			$.ajax({
	             url: actionUrl,
	             cache: false,
	             dataType:"json",
	             async:true,
	             error : function(textStatus, errorThrown) {  
	                 ctools.alert("系统ajax交互错误: " + textStatus);  
	             }, 
	             success : function (data)
	             {
	             		if(data){
	             		var datas=data;
	             		for(var i=0;i<datas.length;i++){
	            			 var shareItem = datas[i];
	            			 
	            			 if(roleID == shareItem['roleId']){continue;}//分享待选中排除自己
	            			 if('2' == shareItem['authorityType']){continue;}//权限类型为特殊的排除
	            			 
	            			 
	            			 var uiItem = $('<div>');
	            			 var uiChkbox = $('<input type="checkbox" name="shareRoleIds"/>');
	            			 
	            			 if(window.shareInfoIni && shareInfoIni[shareItem['roleId']] != null){
	            				 console.log(window.shareInfoIni);
	            				 uiChkbox.attr('checked','checked');
	            			 }
	            			 uiChkbox.attr('id','shareRoleIds_'+shareItem['roleId']);
	            			 uiChkbox.val(shareItem['roleId']+'');//设置checkbox的值
	            			 uiItem.append(uiChkbox);
	            			 
	            			 if (shareItem['isMiddleBack'] == 'Y') {
	            				 uiItem.append(' (中后台角色)'+shareItem['roleName']);
	            			 } else {
	            				 uiItem.append(' '+shareItem['roleName']);
	            			 }
	            			 container.append(uiItem);
	            		 }
 	             		//绑定ICheck样式
 	             		WASP_WIDGET.triggerICheck();
	             		
	             	 }else{
	             		container.html("没有数据！");
	            	 }
	             }
	         });
		}
};

var $roleList=$("#roleList");
$(function(){
	$roleList.jqGrid({   
				url:PATH_PREFIX+'roleListPage.do',    
				caption:'角色维护列表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',  
				datatype: "json",
				colNames:["角色ID","角色类型编码","员工ID","角色名称","角色类型","权限类型","状态","所属岗位","关联操作角色","是否为部门资源默认角色","是否为部门人员默认角色","关联部门", '是否中后台角色', '操作'],       
				colModel:[  {name:'roleId',index:'ROLE_ID', hidden:true,key:true},
				            {name:'roleType',index:'ROLE_TYPE', hidden:true},
				            {name:'empId',index:'EMP_ID', hidden:true},
							{name:'roleName',index:'ROLE_NAME',width: 40, resizable:true,align:'left',formatter: WASP_ROLE.getViewHtml,sortable:false},  
							{name:'roleTypeName',index:'ROLE_TYPE_NAME',width: 30, resizable:true,align:'left',sortable:false},  
							{name:'authorityType',index:'AUTHORITY_TYPE',width: 20, resizable:true,align:'left',formatter:'select',
			                	  editoptions: { value: {1:'普通',2:'特殊'}},sortable:false},
							{name:'statName',index:'STATNAME', width: 20, resizable:true,align:'left', sortable:false},
							{name:'postTitle',index:'POST_TITLE', width: 20, resizable:true,align:'left', sortable:false},
							{name:'operRoleName',index:'OPER_ROLE_NAME', width: 20, resizable:true,align:'left', sortable:false},
							{name:'isDemptName',index:'IS_DEMPT_NAME', width: 20, resizable:true,align:'left', sortable:false},
							{name:'isDemptPerName',index:'IS_DEMPT_PER_NAME', width: 20, resizable:true,align:'left', sortable:false},
							{name:'orgName',index:'ORG_NAME', width: 20, resizable:true,align:'left', sortable:false},
							{name:'isMiddleBackName',index:'isMiddleBackName', width: 20, resizable:true,align:'left', sortable:false},
							{name:'option',index:'option', width: 20, resizable:true,align:'left',sortable:false}
						],
				rowNum: 20,
		        rowList: [20, 30, 50],
		        rownumbers: true,
		        rownumWidth: 50,
		        prmNames: { search: "search", page: "pageNo", rows: "limit" },
		        height: 'auto',
		        width: false,
		        autowidth:true,
		        editurl: '',
		        viewrecords: true,
		        cellEdit: false,
		        shrinkToFit: true,
		        grouping: false,
		        jsonReader: {
		            root: "items", //结果集
		            records: "total", //总记录数 
		            total: "pageCount", //总页数
		            page: "pageNo", //当前页 
		            repeatitems: false // (4) 
		        },  
				multiselect:false,
				pager: "#rolePage", 							
				viewrecords: true,
				hidegrid: false, 
				gridComplete: function(){
					var ids = $roleList.jqGrid('getDataIDs');
					for(var i=0;i < ids.length;i++){
						var role_ID = ids[i];
					 
						var rowData = $roleList.jqGrid('getRowData', role_ID); 
						var se = '<a id="lineEdit'+role_ID+'" href="javascript:void(0);" class="btn btn-link btn-jqgrid" title="修改" onclick="WASP_ROLE.updateRole(\''+rowData.roleId+'\')">修改</a>';
						$roleList.jqGrid('setRowData',ids[i],{option:se});
					}	
				}
			});
		
		$roleList.navGrid('#rolePage',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
		$roleList.jqGrid('setFrozenColumns');
		jqGridResize($roleList);
		
	});

/**
 * 查询
 * @param flag
 */
function queryByCondtion (flag){
	var roleName = $.trim($("#q-roleName").val());
	var roleType = $.trim($("#q-roleType").val());
	var empId = $.trim($("#q-empId").val());
	var postTitle = $.trim($("#q-postTitle").val());
	var orgName = $.trim($("#q-orgName").val());
	var operRoleName = $.trim($("#q-operRoleName").val());
	var isMiddleBack = $("#q-isMiddleBack").val();
	
    var postData = $roleList.jqGrid("getGridParam", "postData");
	$.extend(postData,{ 
		'sp[roleName]': roleName,
		'sp[roleType]': roleType,
		'sp[empId]': empId,
		'sp[postTitle]': postTitle,
		'sp[orgName]': orgName,
		'sp[operRoleName]': operRoleName,
		'sp[isMiddleBack]': isMiddleBack
	 });
	 if (flag){
		$roleList.trigger("reloadGrid",[{page:1}]);//重新载入Grid表格
	}else{
		$roleList.trigger("reloadGrid");//重新载入Grid表格
	}       
};

//对按钮绑定全屏事件
$(document).on('click', '.btn-fullscreen', function(){
    var $wrapper = $(this).parents('.fullscreen-wrapper')[0];
    toggleFullScreen(document.documentElement);
    //全屏的时候将几个模态框放到下面去
    $('.modal[role="dialog"]').appendTo($wrapper);
});

function initRadios(){
    //单选框
	WASP_WIDGET.triggerIRadio("input[name='authorityType']",function(value){
		WASP_ROLE.showShareInfo();
	});
	
}